<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 产品
 * @author www.dingwei.cn
 */
class Product extends MY_Controller {
	
	const PRODUCT_DEUBG = FALSE;//参数调试输出log
	/**
	 * 商家模型
	 * @var MerchantUserModel
	 */
	public $mMerchant;
	
	/**
	 * 分类模型
	 * @var ConsumerCategoryModel
	 */
	public $mCategory;
	
	/**
	 * 评论模型
	 * @var MerchantCommentModel
	 */
	public $mComment;
	
	/**
	 * 产品模型
	 * @var ConsumerProductModel
	 */
	public $mProduct;
	
	/**
	 * 订单模型
	 * @var ConsumerOrderModel
	 */
	public $mOrder;
	
	/**
	 * 支付模型
	 * @var ConsumerPayModel
	 */
	public $mPay;
	
	/**
	 * 购物车模型
	 * @var ConsumerCartModel
	 */
	public $mCart;
	
	/**
	 * 活动模型
	 * @var ConsumerPromotionModel
	 */
	public $mPromotion;
	
	/**
	 * 活动模型
	 * @var MerchantPromotionModel
	 */
	public $mMerPromotion;
	
	/**
	 * 地址模型
	 * @var ConsumerAddressModel
	 */
	public $mAddress;
	
	/**
	 * 
	 * @var ConsumerMessageModel
	 */
	public $mMsg;
    /**
     *
     * @var ConsumerUserModel
     */
    public $mUser;
    /**
     *
     * @var MerchantMessageModel
     */
	public $mMerMsg;

    /**
     * @var DlnOrderModel
     */
	public $mDln;
	public function __construct(){
		parent::__construct();
		$this->loadModel('ConsumerCategoryModel', 'mCategory', 'consumer');
		$this->loadModel('MerchantCommentModel', 'mComment', 'merchant');
		$this->loadModel('ConsumerProductModel', 'mProduct', 'consumer');
		$this->loadModel('ConsumerCartModel', 'mCart', 'consumer');
	}
	
	public function getMerchantCart(){
		//表单验证
		$vConf = array(
				array('merchant_id', '类型', 'required|is_natural_no_zero'),
		);
		$this->formDataValidation($vConf);
		
		$merchantId = trim(post('merchant_id'));
		
		$this->loadModel('MerchantUserModel', 'mMerchant', 'merchant');
		$this->loadModel('ConsumerCartModel', 'mCart','consumer');
		/**
		 * 商家信息
		 * @var array $tShop
		 */
		
		$tData = $this->mMerchant->getShopInfo($merchantId,true);
		if (! $tData){
			$this->appReturn(0,'商家不存在');
		}
		
		$tUser = array();
		$tData = array();
        $lunch_box_fee = 0; //打包费
		$sessionid = decode(post('sessionid'));
		if ($sessionid){
			$tUser = $this->mUser->getInfoBySessionid($sessionid);
		}
		
		if ($tUser){
			$tCart = $this->mCart->getList($tUser['id'],$merchantId);
			
			if (isset($tCart[$merchantId])){

				foreach ($tCart[$merchantId] as $k=>$v){
					$v['property'] = array_values($v['property']);
					$v['property_str'] = implode('/', $v['property']);
                    $lunch_box_fee = $lunch_box_fee + $v['lunch_box_fee'];
					$tData[] = $v;
				}
			}
		}

		$data = [
		    'lunch_box_fee'=>sprintf('%.2f',$lunch_box_fee),
            'list'=>$tData
        ];
		$this->appReturn(1,'',$data);
	}
		
	/**
	 * 获取商家信息
	 */
	public function getMerchantInfo(){
		//表单验证
		$vConf = array(
				array('merchant_id', '店铺id', 'required|is_natural_no_zero'),
		);
		$this->formDataValidation($vConf);
		
		$merchantId = trim(post('merchant_id'));
		
		$this->loadModel('MerchantUserModel', 'mMerchant', 'merchant');
		$this->loadModel('MerchantPromotionModel', 'mMerPromotion', 'merchant');
		$this->loadModel('ConsumerUserModel', 'mConsumer', 'consumer');
		
		/**
		 * 商家信息
		 * @var array $tShop
		 */
		
		
		$tData = $this->mMerchant->getShopInfo($merchantId,true);
		if (! $tData){
			$this->appReturn(0,'商家不存在');
		}

        //预计送达时间
        $tBusiness = $this->mMerchant->getBusinessMerchant(array($merchantId));
        $expectArriveTime = '';
        if($tData['merchant']['business'] == 2 && !$tBusiness){
            $_time = $this->mMerchant->getBusinessTimeList($merchantId,true);
            $_for = getCustomConfig('expect_take_time');
            $_other = $this->mSetting->get('rob_expect_time', 'deliveryman');
            $arriveTime = appArriveTime($_time,0,0,0,20);
            if($arriveTime['today']){
                $expectArriveTime = $arriveTime['today'][0].'起送';
            }elseif ($arriveTime['other']){
                $expectArriveTime = '明日'.$arriveTime['other'][0].'起送';
            }
        }

		$promotion = array();
        //代金劵
        $tPromotion = $this->mMerPromotion->getCouponListByMerchantIds(array($merchantId));
        //代金劵
        if (isset($tPromotion[$merchantId])){
            $promotion[] = '下单即送代金劵';
        }
        //满减劵
        $tFullCut = $this->mMerPromotion->getFullCutListByMerchantIds(array($merchantId));
        $rule = '';
        //满减劵
        if (isset($tFullCut[$merchantId]['rule'])){
            $full = json_decode($tFullCut[$merchantId]['rule'],true);
            if ( ! $full){
                $full = array();
            }

            foreach ($full as $fk=>$fv){
                if ($fv['max_money']){
                    if ($rule){
                        $rule .= ',';
                    }

                    $rule .= '满'.$fv['max_money'].'减配送费'.$fv['money'];
                }
            }
        }
        if($rule){
            $promotion[] = $rule;
        }
        // 首单减免
        if ($tData['profile']['first_order_reduce'] > 0){
            $promotion[] = '首单减免'.$tData['profile']['first_order_reduce'].'元';
        }
        $tData['promotion'] = $promotion;
        //周营业日
        $weekarray=array("","周一","周二","周三","周四","周五","周六","周日"); //定义一个数组
        $wk = '';
        if($tData['profile']['business_week']){

            $week = array_filter(explode(',',$tData['profile']['business_week']));
            foreach ($week as $k=>$v){
                $wk .= $weekarray[$v];
                if($k != count($week)){
                    $wk .= '、';
                }
            }
        }
        $tData['profile']['business_week'] = $wk;
        //营业时间
        $timeStr = '';
        foreach ($tData['profile']['business_time'] as $t){
            $timeStr .= $t['business_time_start'].'-'.$t['business_time_end'].' ';
        }
        $tData['profile']['business_time'] = $timeStr;
        $tData['profile']['business_desc'] = $expectArriveTime;

        $tData['bonus'] = (object)array();//商盟红包

		//分享信息
		$this->loadModel('AdmSettingModel', 'mSetting', 'admin');
		$tShare = $this->mSetting->get('sharp_title,sharp_icon,sharp_url,sharp_desc');
		$tShare['sharp_icon'] = getImage($tShare['sharp_icon'],'og');
		$tData['share']['title'] = '赶快下载APP来领取';
		$tData['share']['url']  = $tShare['sharp_url'];
		$tData['share']['desc']  = $tShare['sharp_desc'].$tData['merchant']['shop_name']."的红包吧！";
		$tData['share']['icon']  = $tShare['sharp_icon'];
		/**
		 * 是否收藏
		 */
		
		$tUser = array();
		$sessionid = decode(post('sessionid'));
		if ($sessionid){
			$tUser = $this->mUser->getInfoBySessionid($sessionid);
		}
		$tData['is_Collection'] = "1";//没有收藏
		if ($tUser && $this->mUser->hasCollection($tUser['id'], $merchantId, 1)){
			$tData['is_Collection'] = "2";//有收藏
		}
		
		$this->appReturn(1,'',$tData);
	}
	
	
	/**
	 * 获取商家评论列表
	 */
	public function getCommentList(){
		//表单验证
		$vConf = array(
				array('merchant_id', '商家id', 'required|is_natural_no_zero'),
				array('page', '分页', 'required|is_natural_no_zero'),
 				array('product_id', '产品id', 'is_natural_no_zero'),
		);
		$this->formDataValidation($vConf);
		
		$merchantId = trim(post('merchant_id'));
		$page = trim(post('page'));
		$productId = post('product_id');

		$this->loadModel('MerchantUserModel', 'mMerchant', 'merchant');
		
		//验证商家是否存在
		if ( ! $this->mMerchant->getInfo($merchantId)){
			$this->appReturn(0,'商家不存在');
		}
		
		$tA = $this->mComment->appGetCommentList($merchantId, $productId, $page);
        $this->appReturn(1,'',$tA);
	}
	
	/**
	 * 获取产品列表[暂时未用]
	 */
	public function getProductList(){
		//表单验证
		$vConf = array(
				array('merchant_id', '商家id', 'required|is_natural_no_zero'),
				array('custom_id', '自定义分类id', 'required'),
				array('page', '分页', 'required|is_natural_no_zero'),
		);
		$this->formDataValidation($vConf);
		
		$merchantId = trim(post('merchant_id'));
		$customId = trim(post('custom_id'));
		$page = trim(post('page'));
		
		$this->loadModel('MerchantUserModel', 'mMerchant', 'merchant');
		
		//判断商家是否
		if ( ! $this->mMerchant->getInfo($merchantId)){
			$this->appReturn(0,'商家不存在');
		}
		
		//分类是否
		if ( ! in_array($customId, array('recommend'))){
			if ( ! $this->mCategory->getCustomInfo($customId)){
				$this->appReturn(0,'分类不存在');
			}
		}
		
		$tA = $this->mProduct->appGetList($merchantId, $customId, $page);
		
		$this->appReturn(1,'',$tA);
	}

	/**
	 * 获取产品列表
	 */
	public function getProductAll(){
		//表单验证
		$vConf = array(
				array('merchant_id', '商家id', 'required|is_natural_no_zero'),
		);
		$this->formDataValidation($vConf);
		
		$merchantId = trim(post('merchant_id'));
		$sessionid = decode(post('sessionid'));
		
		$userId = 0;
		if ($sessionid) {
			$tUser = $this->mUser->getInfoBySessionid($sessionid);
			$userId = $tUser['id'];
		}
		$this->loadModel('MerchantUserModel', 'mMerchant', 'merchant');
		
		//判断商家是否
		if ( ! $this->mMerchant->getInfo($merchantId)){
			$this->appReturn(0,'商家不存在');
		}
		$tData = array();
		
		//获取所有分类
		$tCustom = $this->mCategory->getCustomList($merchantId);
		//获取所有商品
		$tA = $this->mProduct->appGetAll($merchantId,$userId, true);
		
		if(! $tA){
			$this->appReturn(1,'该没有商品');
		}
		
		$tProductIds = array();
		foreach ($tA as $k=>$v){
			if (!in_array($v['id'], $tProductIds)){
				$tProductIds[] = $v['id'];
			}
		}
		
		//获取产品属性
		$tProperty = $this->mProduct->getPropertyListByIds($tProductIds);
		
		//获取变体
		$tVariant = $this->mProduct->getPropertyVariantListByIds($tProductIds);
        //获取属性
        $tags = $this->mProduct->getTagsListByIds($tProductIds);

        foreach ($tA as $k=>$v){
			$v['property'] = isset($tProperty[$v['id']])?$tProperty[$v['id']]:array();
			$v['variant'] = isset($tVariant[$v['id']])?$tVariant[$v['id']]:array();
            $v['tags'] = isset($tags[$v['id']])?1:0;
			$tData[$v['category_id']][] = $v;
		}
			
		
		
		foreach ($tCustom as $k=>$v){
			if (isset($tData[$v['id']])){
				//分类下没有商品，则删除
				$tCustom[$k]['product'] = $tData[$v['id']];
			}else{
				unset($tCustom[$k]);
			}
		}
		
		$tCustom = array_values($tCustom);
		$this->appReturn(1,'',$tCustom);
	}
	
	
	/**
	 * 获取商家首页红包
	 */
	public function getCouponList(){
		//表单验证
		$vConf = array(
				array('merchant_id', '商家id', 'required|is_natural_no_zero'),
		);
		$this->formDataValidation($vConf);
		
		$tA = array(
				''
		);
	}
	
	/**
	 * 获取产品详情
	 */
	public function getProductInfo(){
		//表单验证
		$vConf = array(
				array('product_id', '产品id', 'required|is_natural_no_zero'),
				array('merchant_id', '商家id', 'required|is_natural_no_zero'),
		);
		$this->formDataValidation($vConf);
		
		$merchantId = trim(post('merchant_id'));
		$productId = trim(post('product_id'));
// 		$merchantId = 13;
// 		$productId = 93;
		//获取产品
		$tA = $this->mProduct->getInfo($productId,$merchantId);
		if ( ! $tA){
			$this->appReturn(0,'产品不存在');
		}
		// 获取商家起送价格
        $this->loadModel('MerchantUserModel', 'mMerchant','merchant');
		$merchant = $this->mMerchant->getInfo($merchantId);
        $tA['min_consume'] = $merchant['min_consume'];
        unset($merchant);

		//获取产品详情
		$tA['detail'] = array();
		$tDetail = $this->mProduct->getDetailList($productId);
		
		//print_r($tDetail);
		$html = $this->view('product/info',['info'=>$tDetail],0,0,0,true);
	
/* 		foreach ($tDetail as $k=>$v){
			if ($v['type'] == 2){
				$v['content'] = $v['content'];
				$tA['detail'][] = $v;
			}
			$tA['detail'][] = $v;
		} */
		 
		$this->loadModel('ConsumerAddressModel', 'mAddress','consumer');
		$tAddress = $this->mAddress->getDefaultAddress($this->userId);
        if (empty((array)$tAddress)){
            $tA['shipping_fee'] = '0';
        }else{
            $tA['shipping_fee'] = (string)$this->shippingFreight(3,$tA['weight'], $tAddress['province'], $tAddress['city'], $tAddress['county']);
        }

		//获取评论列表
		$tA['comment'] = $this->mComment->appGetCommentList($merchantId,$productId,1);
		
		//获取产品属性
		$tA['property'] = $this->mProduct->getPropertyList($productId);
		
		//获取变体
		$tA['variant'] = $this->mProduct->getPropertyVariantList($productId);
        //获取属性
        $tags = $this->mProduct->getTagsListByIds(array($productId));
        $tA['tags'] = isset($tags[$productId])?1:0;

        $tA['detail'] = $html;
		
		
		$this->appReturn(1,'',$tA);
	}
	
	/**
	 * 更换规格
	 */
	public function getProperty(){
		if ($this->isDEBUG){
			$productId = 78;
			$sort = 1;
			$this->userId = 8;
		}else{
		
		//表单验证
 		$vConf = array(
				array('product_id', '产品id', 'required|is_natural_no_zero'),
				array('sort', '产品规格序号', 'required'),
		); 
		
		$this->formDataValidation($vConf);
		
		$productId = post('product_id');
		$sort = post('sort');
		}

		
		//获取产品
		$tA = $this->mProduct->getInfo($productId);
		if ( ! $tA){
			$this->appReturn(0,'产品不存在');
		}
		
		//获取购物车信息
		$tCart = $this->mCart->getCartProductInfo($productId,$sort,$this->userId);
		if ( ! $tCart){
			$this->appReturn(0,'购物车商品不存在');
		}
		
		//获取已经选择的组合
		$tVariant = $this->mProduct->getPropertyVariantInfo($productId, $sort);
		if ( ! $tVariant){
			$this->appReturn(0,'该商品组合不存在');
		}
// 		p($tVariant);
		//获取产品属性
		$tData['property'] = $this->mProduct->getPropertyList($productId);
		
		//获取变体
		$tData['variant'] = $this->mProduct->getPropertyVariantList($productId);
		
		$html = $this->view('cart/specification',[
				'json'=>json_encode($tData),		//产品组合规格
				'product_id'=>$productId,			//产品id
				'sort'=>$sort,						//当前产品组合sort
				'varaint'=>$tVariant['property'],   //产品默认组合
				'quantity'=>isset($tCart['quantity'])?$tCart['quantity']:0,     //当前产品数量
		],'', '', '', true);
		
		if ($this->isDEBUG){
			echo $html;
			exit();
		}
		
		$data = array(
				'name'=>$tA['name'],
				'icon'=>$tA['icon']['og'],
				'quantity'=>isset($tVariant['quantity'])?$tVariant['quantity']:"0",
				'price'=>$tVariant['price'], //组合单价
				'html'=>$html,
		);
		$this->appReturn(1,'',$data);
	}
	
	/**
	 * 更换规格
	 */
	public function getProductProperty(){
//        $this->isDEBUG = true;
		if ($this->isDEBUG){
			$productId = 165;
		}else{
			//表单验证
			$vConf = array(
					array('product_id', '产品id', 'required|is_natural_no_zero'),
			);

			$this->formDataValidation($vConf);

			$productId = post('product_id');
		}
		
		//获取产品
		$tA = $this->mProduct->getInfo($productId);
		if ( ! $tA){
			$this->appReturn(0,'产品不存在');
		}

		//获取产品属性
		$tData['property'] = $this->mProduct->getPropertyList($productId);
		
		//获取变体
		$tData['variant'] = $this->mProduct->getPropertyVariantList($productId);
        //获取属性
        $tData['tags'] = $this->mProduct->getTagsList($productId);

		$html = $this->view('cart/specification',[
				'json'=>json_encode($tData),		//产品组合规格
				'product_id'=>$productId,			//产品id
				'sort'=>'0',						//当前产品组合sort
				'varaint'=>json_encode(array()),   //产品默认组合
                'tags'=>json_encode(array()),   //产品默认组合
				'quantity'=>'0',     //当前产品数量
				'goods_price'=>$tA['goods_price'],     //当前产品数量
				'goods_number'=>$tA['quantity'],     //当前产品数量
		],'', '', '', true);

		if ($this->isDEBUG){
			echo $html;
			exit();
		}
		
		$data = array(
				'name'=>$tA['name'],
				'icon'=>$tA['icon']['og'],
				'quantity'=>"0",
				'html'=>$html,
		);
		$this->appReturn(1,'',$data);
	}
		
	/**
	 * 预览订单
	 */
	public function previewOrder(){
		//---------------------------------------------\
        //MY_Controller 中 将变量设置为 true 即可开启线下测试，
        //还有consumer 配置中，设置不过滤该链接
//        $this->isDEBUG = true;
        if ($this->isDEBUG){
            $param = '[{"product_id":"48","sort":"0","quantity":"1"}]';
            $this->userId = 1;
            $product = json_decode($param,true);
        }else{
        	//表单验证
        	$vConf = array(
        			array('product', '产品参数', 'required'),
        	);
        	$this->formDataValidation($vConf);

        	$product = json_decode(post('product'),true);
        }
		//---------------------------------------------
		
		//加载模型
		$this->loadModel('MerchantUserModel', 'mMerchant','merchant');
		$this->loadModel('ConsumerProductModel', 'mProduct','consumer');
		$this->loadModel('MerchantPromotionModel', 'mMerPromotion','merchant');
		$this->loadModel('ConsumerOrderModel', 'mOrder','consumer');
        $this->loadModel('AdmSettingModel', 'mSett', 'admin');
        $this->loadModel('ConsumerPromotionModel', 'mPromotion','consumer');
        $this->loadModel('ConsumerPostalCardModel', 'mPostalCard');

		//验证产品格式

		$tProduct = $this->mProduct->canAddOrder($this->userId, $product);
		if ( ! is_array($tProduct)){
			$this->appReturn(0,(is_string($tProduct) ? $tProduct : '格式错误'));
		}

		$tMerchantIds = array();

		foreach ($tProduct as $k=>$v){
			if (!in_array($v['merchant_id'], $tMerchantIds)){
				$tMerchantIds[] = $v['merchant_id'];
			}
			
		}
		if (! $tMerchantIds){
			$this->appReturn(0,'商品商家不存在');
		}
		
		//获取商户信息
		$tMerchant = $this->mMerchant->getInfoByIds($tMerchantIds);
		if (! $tMerchant){
			$this->appReturn(0,'商品商家不存在');
		}
		
		//批量获取商户满减劵
		$tFullCut = $this->mMerPromotion->getFullCutListByMerchantIds($tMerchantIds);

        /**
         * 获取首单减免
         */
        $tFirstOrder = $this->_firstOrder($tMerchantIds);

		/**---------------------------------------------
		 * 多商品运费筛选
		 * 备注：逻辑为，如果该商家的商品中，有一个为包邮，则不需要在寻找邮费。如果不是就赋值运费，运费的来源是商品的总质量+地区计算得来
		 */
		$this->loadModel('ConsumerAddressModel', 'mAddress','consumer');
		$tempLocation = $tMerchant[$tMerchantIds[0]];
		$Address = $this->mAddress->getDefaultAddress($this->userId,$tempLocation['latitude'],$tempLocation['longitude']);

		if ( ! is_array($Address)){
			$Address = (array)$Address;
		}
		$tmAmount = $this->_orderFee($tProduct, $product, empty($Address['id'])?0:$Address['id']);

        /**----------------------------------
         * 获取商家多段时间[单个商家]
         */
        $tTime = $this->mMerchant->getBusinessTimeList($tMerchantIds[0]);
        $week_s = ['','周一','周二','周三','周四','周五','周六','周日'];
        $week_str = explode(',', $tMerchant[$tMerchantIds[0]]['business_week']);
        $tWeek = array();
        foreach ($week_str as $kk=>$vv){
            if ($vv){
                $tWeek[] = $week_s[$vv];
            }
        }

// 		p($tProduct);
		//预览订单
		$tOrder = array();
		$total = 0;//总金额
		foreach ($tProduct as $k=>$v){

			//如果没有规格
			if ( ! empty($v['property'])){
				$v['property'] = implode('/', json_decode($v['property'],true));
			}else{
				$v['property'] = '';
			}
			$v['icon'] = getImage($v['icon'],'og');


			//店铺信息
            $shop = array(
                'shop_name' => isset($tMerchant[$v['merchant_id']]['shop_name']) ? $tMerchant[$v['merchant_id']]['shop_name']:'',
                'portrait' => $tMerchant[$v['merchant_id']]['portrait'],
                'mobile' => $tMerchant[$v['merchant_id']]['mobile'],
                'latitude' => $tMerchant[$v['merchant_id']]['latitude'],
                'longitude' => $tMerchant[$v['merchant_id']]['longitude'],
                'address' => $tMerchant[$v['merchant_id']]['address'],
                'time' => $tTime,
                'week' => $tWeek?implode(',', $tWeek):'周一,周二,周三,周四,周五,周六,周日',
            );
			$tOrder[$v['merchant_id']]['name'] = isset($tMerchant[$v['merchant_id']]['shop_name']) ? $tMerchant[$v['merchant_id']]['shop_name']:'';
			$tOrder[$v['merchant_id']]['shop_info'] = $shop;
			$tOrder[$v['merchant_id']]['is_bonus'] = $tMerchant[$v['merchant_id']]['able_use_coupon']; //是否支持红包
			$tOrder[$v['merchant_id']]['is_coupon'] = $tMerchant[$v['merchant_id']]['able_cash_coupon'];//是否支持代金劵
			$tOrder[$v['merchant_id']]['shop_type'] = $tMerchant[$v['merchant_id']]['shop_type'];//商家类型
			
			//邮费
			if ($tmAmount){
    			$tOrder[$v['merchant_id']]['is_free_shipping'] = $tmAmount[$v['merchant_id']]['is_free_shipping'];
    			$tOrder[$v['merchant_id']]['shipping_fee'] = $tmAmount[$v['merchant_id']]['shipping_fee'];
			}else{
			    $tOrder[$v['merchant_id']]['is_free_shipping'] = 1;
			    $tOrder[$v['merchant_id']]['shipping_fee'] = 0;
			    $tmAmount[$v['merchant_id']]['shipping_fee'] = 0;
                $tmAmount[$v['merchant_id']]['is_free_shipping'] = 1;
			}

			$v['price'] = $v['variant_id']>0?$v['v_price']:$v['goods_price'];

			//商品
			$tOrder[$v['merchant_id']]['list'][] = $v;

			//计算总金额
			$total = $total + $v['goods_price']*$v['b_quantity'];
		}
//		p($tOrder);
		/**
		 * 订单数据数组
		 * @var array $tData
		 */
		$tData = array();
		//是否在店铺营业时间内
        $tBusiness = $this->mMerchant->getBusinessMerchant($tMerchantIds);

		foreach ($tOrder as $k=>$v){
			$tempProduct = [];
			$amount = 0;
            //打包费
            $lunch_box_fee = 0;
			foreach ($v['list'] as $kk=>$vProduct){

                $lunch_box_fee = $lunch_box_fee + $vProduct['lunch_box_fee'];

				$tempProduct[] = array(
						'product_id'=>$vProduct['id'],
						'sort'=>empty($vProduct['sort'])?'0':$vProduct['sort'],
						'quantity'=>$vProduct['b_quantity'],
						'price'=>$vProduct['price'],
                        'tags'=>$vProduct['tags'],
				);
				$amount += $vProduct['price']*$vProduct['b_quantity'];

			}
			//根据商家 与订单金额 获取满减额度
			$fullcut = array('money'=>0,'max_money'=>0);
			if ($tFullCut){
				$fullcut = $this->mMerPromotion->getSatisfyFullCut($tFullCut[$k]['rule'], $amount); //商品的总价
			}

            //首单减免
            $firstOrder = 0;
            if (isset($tFirstOrder[$k]) && ! empty($tFirstOrder[$k])){
                $firstOrder = $tFirstOrder[$k];
            }
            /**
             * 红包【单个商家】
             */
            $tBonus = $this->mPromotion->appGetBonusLogList($this->userId,1,1,false,$total);
            /**
             * 代金券[单个商家]
             */
            $tCoupon = $this->mPromotion->appGetCouponLogList($this->userId,1,1,false,$total,$tMerchantIds[0]);

            $tPostalCard = $this->mPostalCard->appGetBonusLogList($this->userId,1,1,false,true,true);

            $_time = $this->mMerchant->getBusinessTimeList($k,true);

            $_for = getCustomConfig('expect_take_time');
            $_other = $this->mSett->get('rob_expect_time', 'deliveryman');
            $arriveTime = appArriveTime($_time,$_for,$_other,$tMerchant[$k]['expect_arrive_time'],20);
            $self_lifting_time = appArriveTime($_time,$_for,0,0,20);


            //App需要的数据
			$tData[] = array(
					'merchant_id'=>$k,
					'is_business'=>isset($tBusiness[$tMerchantIds[0]]) ? 2:1,
					'shop_info'=>$v['shop_info'],
					'product'=>$tempProduct,
					'coupon_id'=>'0',//默认代金券
			        'amount'=>$amount,                      //该商家订单总金额
					'bonus_id'=>'0',                        //默认红包
                    'postal_card_id'=>"0",                  // 包邮卡
					'expense_type'=>"0",                    //默认0
					'shop_type'=>$v['shop_type'],
					'full_cut'=>$fullcut['money'],          //满减
                    'first_order_reduce' => $firstOrder,
                    'lunch_box_fee'=>$lunch_box_fee,        //合计打包费
                    'expect_arrive_time'=>'',                    //送达时间
                    'expect_arrive_time_s'=> $arriveTime,                    //送达时间
                    'self_lifting_time'=> $self_lifting_time,                    //自提时间 -- 送达时间
                    'shortage_handing'=>['value'=>'','remark'=>''],                 //缺货处理
                    'shortage_handing_s'=>$this->mOrder->getShortage(),//缺货处理的选项
// 					'shipping_fee'=>$tmAmount[$k]['shipping_fee'],
					'remark'=>'',
			);
			//累加运费
			$total +=$tmAmount[$k]['shipping_fee'] + $lunch_box_fee;

			//页面显示需要的数据
            $tOrder[$k]['lunch_box_fee'] = round($lunch_box_fee, 2);//打包费
            $tOrder[$k]['first_order_reduce'] = $firstOrder;//首单减免
            $tOrder[$k]['full_cut'] = $fullcut;//满减活动
			$tOrder[$k]['full_cut_str'] = '暂无活动';
			if ($fullcut['money']){
				$tOrder[$k]['full_cut_str'] = '满'.$fullcut['max_money'].'减配送费'.$fullcut['money'];
			}
            $tOrder[$k]['bonus'] = $tBonus?count($tBonus).'张可用':'暂无可用';
            $tOrder[$k]['coupon'] = $tCoupon?count($tCoupon).'张可用':'暂无可用';
            $tOrder[$k]['postal_card'] = $tPostalCard?count($tPostalCard).'张可用':'暂无可用';
		}

        if(isset($arriveTime['today']) && $arriveTime['today']){
            if(isset($tBusiness[$tMerchantIds[0]])){
                $send_out = '立即送达 (预计:'.$arriveTime['today'][0].')';
            }else{
                $send_out = '今日'.$arriveTime['today'][0].'';
            }

        }else{
            $send_out = '明日'.$arriveTime['other'][0].'';
        }

		$data = array(
				'order'=>$tOrder,
				'total'=>$total,
                'is_business' => isset($tBusiness[$tMerchantIds[0]]) ? 2:1,
				'send_our_immediately'=>$send_out,
		);

//		$html = $this->view('cart/pay',$data);
		$html = $this->view('cart/pay',$data, '', '', '', true);
		if ($this->isDEBUG){
			echo $html;
			exit();
		}
		$this->appReturn(1,'',['param'=>$tData,'html'=>$html]);
	}

	/**
	 * 商品下单[商盟]
	 */
	public function orderSm(){
		//表单验证
		$vConf = array(
				array('param', '其他参数参数', 'required'),
		);
		$this->formDataValidation($vConf);

		$param = json_decode(post('param'),true);
		$address_id = post('address_id');//地址id
		
// 		$param = json_decode('[{"amount":128.5,"bonus_id":"7","coupon_id":"2","expense_type":2,"fee":0.0,"merchant_id":"3","product":[{"price":"5","product_id":"260","quantity":"1","sort":"0"}],"red":0.0,"remark":"","ticket":0.0},{"amount":61.5,"bonus_id":"8","coupon_id":"5","expense_type":2,"fee":0.0,"merchant_id":"13","product":[{"price":"20.50","product_id":"72","quantity":"3","sort":"1"}],"red":0.0,"remark":"","ticket":0.0}]',true);
// 		$address_id = 19;
		if ( ! $param){
			$this->appReturn(0,'提交的参数格式错误');
		}

		/**
		 * 加载模型
		 */
		$this->loadModel('MerchantUserModel', 'mMerchant','merchant');
		$this->loadModel('ConsumerProductModel', 'mProduct','consumer');
		$this->loadModel('ConsumerOrderModel', 'mOrder','consumer');
		$this->loadModel('ConsumerPayModel', 'mPay','consumer');
		$this->loadModel('ConsumerPromotionModel', 'mPromotion','consumer');
		$this->loadModel('ConsumerAddressModel', 'mAddress','consumer');
		$this->loadModel('MerchantPromotionModel', 'mMerPromotion','merchant');
		$this->loadModel('AdmSettingModel', 'mSetting','admin');
        $this->loadModel('ConsumerPostalCardModel', 'mPostalCard','consumer');

		/**--------------------------------------------------------------
		 * 验证产品格式
		 */
		$products 	= array();//产品参数数组
		$tParam 	= array();//以商家为标识的数组
		$bBonusIds 	= array();//批量红包id
		$bCouponIds = array();//批量代金劵id
        $postalCardIds = array(); // 包邮卡

		foreach ($param as $k=>$v){
			
			if ( ! $v['expense_type']){
				$this->appReturn(0,'请选择消费模式');
			}
			
			//获取红包id
			if ($v['bonus_id'] && in_array($v['bonus_id'], $bBonusIds)){
				$this->appReturn(0,'一个红包只能使用一个商铺');
			}
			$bBonusIds[] = $v['bonus_id'];
			
			//获取代金劵id
			if ($v['coupon_id'] && in_array($v['coupon_id'], $bCouponIds)){
				$this->appReturn(0,'一个代金劵只能使用一个商铺');
			}
			$bCouponIds[] = $v['coupon_id'];

            if ($v['expense_type'] == 1 && isset($v['postal_card_id']) && $v['postal_card_id'] > 0) {
                $postalCardIds[] = $v['postal_card_id']; // 包邮卡
            }
			//将提交的产品参数合并[为了验证产品正确性]
			$products = array_merge($products, $v['product']);//合并产品参数
			
			//以商家为标识组合[方便后面验证 实时数据 与 app提交的数据对比验证]
			$tParam[$v['merchant_id']] = $v;
		}

		/**----------------------------------------------------------------
		 * 验证产品参数  
		 * 备注：获取数据库中，按商品 以及商品规格的正确性
		 * @var Ambiguous $tProduct
		 */
		$tProduct = $this->mProduct->canAddOrder($this->userId, $products);
		if ( ! is_array($tProduct)){
			$this->appReturn(0,(is_string($tProduct) ? $tProduct : '格式错误'));
		}

		/**-------------------------------------------------------------
		 * 批量获取红包
		 */
		$tBonus = $this->mPromotion->getBonusByIds($bBonusIds,$this->userId);
		$tCoupon = $this->mPromotion->getCouponByIds($bCouponIds,$this->userId);
        // 获取包邮卡
		$tPostalCard = array();
        if(!empty($postalCardIds)) {
            $tPostalCard = $this->mPostalCard->getInfoIds($postalCardIds, $this->userId);
        }

		/**----------------------------------------------------------------
		 * 获取收货地址
		 */
		$tAddress = $this->mAddress->getInfo($address_id,$this->userId);
		
		/**--------------------------------------------
		 * 批量获取商户信息
		 */
		$tMerchantIds = array();
		foreach ($tProduct as $k=>$v){
			if (!in_array($v['merchant_id'], $tMerchantIds)){
				$tMerchantIds[] = $v['merchant_id'];
			}
		}
		
		if (! $tMerchantIds){
			$this->appReturn(0,'商品商家不存在');
		}
		
		$tMerchant = $this->mMerchant->getInfoByIds($tMerchantIds);
		if (! $tMerchant){
			$this->appReturn(0,'商家不存在');
		}
		
		/**
		 * 批量获取商家的满减劵规则
		 */
		$tFullCut = $this->mMerPromotion->getFullCutListByMerchantIds($tMerchantIds);
		
		/**
		 * 获取首单减免
		 */
		$tFirstOrder = $this->_firstOrder($tMerchantIds);
		
		/**---------------------------------------------
		 * 多商品运费筛选
		 * 备注：逻辑为，如果该商家的商品中，有一个为包邮，则不需要在寻找邮费。如果不是就赋值运费，运费的来源是商品的总质量+地区计算得来
		 */
		$tmAmount = $this->_orderFee($tProduct, $products, $address_id);

		/**---------------------------------------------------------------------------------
		 * 订单按商家分组
		 * @var array $tOrder
		 */
		$tOrder = array();
		$sale_quantity = [];//产品总库存集合 记录产品销量

		foreach ($tProduct as $k=>$v){

		    //累加当前产品打包费
            if ( ! isset($tOrder[$v['merchant_id']]['lunch_box_fee'])){
                $tOrder[$v['merchant_id']]['lunch_box_fee'] = 0;
            }

            $tOrder[$v['merchant_id']]['lunch_box_fee'] += $v['lunch_box_fee'];

            //获取价格
			$v['v_price'] = $v['variant_id']?$v['v_price']:$v['goods_price'];

			//初始化商品金额
			if ( ! isset($tOrder[$v['merchant_id']]['product_amount'])){
				$tOrder[$v['merchant_id']]['product_amount'] = 0;
			}
			//邮费模式
			$tOrder[$v['merchant_id']]['is_free_shipping'] = 1;//$tmAmount[$v['merchant_id']]['is_free_shipping'];
			//商品总金额
			$tOrder[$v['merchant_id']]['product_amount'] += $v['v_price'] * $v['b_quantity'];
			//商品
			$tOrder[$v['merchant_id']]['list'][] = $v;
			
			$sale_quantity[$v['id']] = empty($v['sale_quantity']) ? "0" : $v['sale_quantity'];//产品当前销量
		}


		/**-----------------------------------------------------------------------------------
		 * 订单数据 保存订单
		 */
		$tData 		= array();//订单
		$tempCode 	= array();//订单号
		$payCode 	= getOrderCode();//预支付订单号
		$total 		= 0;//总金额

        $expectTakeTime = getCustomConfig('expect_take_time'); // 商家接单时间
        $robExpectTime = $this->mSetting->get('rob_expect_time', 'deliveryman'); // 配送员接单时间

		foreach ($tOrder as $k=>$v){
			$code = getOrderCode();
			$tempCode[] = $code;//存入订单号

			//非包邮
			$total_amount = $v['product_amount'];
			if($tMerchant[$k]['min_consume'] > $total_amount){
			    $this->ajaxReturn(0, '不满足商家起送价');
            }

			$shipping_fee = 0;
			if ($v['is_free_shipping'] == 1 && ($tParam[$k]['expense_type'] == 1) ){
				if ($tmAmount[$k]['shipping_fee'] != $tParam[$k]['fee']){
					$this->appReturn(0,'邮费好像有变动,请重新下单');
				}
				
				//送货上门、非包邮  加上邮费
				$total_amount = $v['product_amount'] + $tmAmount[$k]['shipping_fee']; //[商品金额 + 运费]
				$shipping_fee = $tmAmount[$k]['shipping_fee']; //当前运费[订单实际]
			}

            //验证打包费
            if ($tParam[$k]['lunch_box_fee'] != $v['lunch_box_fee']){
                $this->appReturn(0,'打包费好像有变动,请重新下单');
            }
            $total_amount = $total_amount + $tParam[$k]['lunch_box_fee'];//加上打包费

			//实际支付金额
			$reality_amount = $total_amount;//[总金额 - 优惠]
			
			//代金劵
			$coupon = 0; 
			if (isset($tCoupon[$tParam[$k]['coupon_id']])){
				$coupon = $tCoupon[$tParam[$k]['coupon_id']]['money'];
				if ($total_amount <= $coupon){
					$this->appReturn(0,'总消费太少了，结果让代金劵都抵完了');
				}
				$reality_amount = $reality_amount - $coupon;
			}
			
			//红包
			$bonus = 0;
			if (isset($tBonus[$tParam[$k]['bonus_id']])){
				$bonus = $tBonus[$tParam[$k]['bonus_id']]['money'];
				if ($total_amount <= $bonus){
					//$this->appReturn(0,'总消费太少了，结果让红包都抵完了');
				}
				$reality_amount = $reality_amount - $bonus;
			}

            //包邮卡
            $postalCard = 0;
            if (isset($tParam[$k]['postal_card_id']) && isset($tPostalCard[$tParam[$k]['postal_card_id']])){
                $postalCard = $tPostalCard[$tParam[$k]['postal_card_id']]['money'];
                $sf = $shipping_fee - $postalCard;
                $sf = $sf < 0 ? $shipping_fee : $postalCard;
                $reality_amount = $reality_amount - $sf;
                $postalCard = $sf;
            }

			//根据商家 与订单金额 获取满减额度
			$fullcut = array('money'=>0,'max_money'=>0);

			if ($tFullCut){
				$fullcut = $this->mMerPromotion->getSatisfyFullCut($tFullCut[$k]['rule'], $v['product_amount']);//商品总价
				if ($fullcut['money'] != $tParam[$k]['full_cut']){
					$this->appReturn(0,'满减金额好像有变动,请重新下单');
				}
				$reality_amount = $reality_amount - $fullcut['money'];//实际支付金额 减去满减劵
			}
			
			//首单减免
			$firstOrder = 0;
			if (isset($tFirstOrder[$k]) && ! empty($tFirstOrder[$k])){
				$reality_amount = $reality_amount - $tFirstOrder[$k];//实际支付金额 减去满减劵
				$firstOrder = $tFirstOrder[$k];
			}
			
			//地址
			$address = '';
			$contacts = '';
			$gender = '';
			$mobile = '';
			$province_id = 0;
			$city_id = 0;
			$county_id = 0;
			$latitude = '';
			$longitude = '';
			if ($tAddress){
				$address = $tAddress['address_desc'];
				$contacts = $tAddress['consignee'];
				$gender = $tAddress['gender'];
				$mobile = $tAddress['mobile'];
				$province_id = $tAddress['province'];
				$city_id = $tAddress['city'];
				$county_id = $tAddress['county'];
                $latitude = $tAddress['latitude'];
                $longitude = $tAddress['longitude'];
			}
			
			//设置到订单数据【后面组合订单产品 计算优惠后的实际占比金额】
			$tOrder[$k]['coupon_amout'] = $coupon;
			$tOrder[$k]['bonus_amout'] = $bonus;
            $tOrder[$k]['reality_amount'] = $reality_amount; //用户实际付款
            if ($reality_amount < 0){
                $reality_amount = 0;
            }

            $web_percent =isset($tMerchant[$k]['percent'])?$tMerchant[$k]['percent']:'0';
            $webservice = round($v['product_amount']*$web_percent/100, 2); //平台服务费
            $min_order_web_amount = isset($tMerchant[$k]['min_order_web_amount'])?$tMerchant[$k]['min_order_web_amount']:'0';//保底抽成

            if($webservice < $min_order_web_amount){
                $webservice = $min_order_web_amount;
            }
            $merchantIncome = $reality_amount - $shipping_fee - $webservice + $bonus;//商家收入
            if($merchantIncome <= 0){
                $webIncome = $reality_amount - $shipping_fee;
            }else{
                $webIncome = $webservice - $bonus; //平台收入
            }

            $deliverymanIncome = $shipping_fee;//配送员收入
            //送达时间
            if (strlen($tParam[$k]['expect_arrive_time']) > 0){
//                $expectArriveTime = strtotime(date('Y-m-').str_replace('日', '', $tParam[$k]['expect_arrive_time'].':00'));
                $expectArriveTime = strtotime($tParam[$k]['expect_arrive_time']);
            }else{
                if($tParam[$k]['expense_type'] == 1 ){
                    $expectArriveTime = time() + ($expectTakeTime + $tMerchant[$k]['expect_arrive_time'] + $robExpectTime) * 60;
                    if(empty($tParam[$k]['expect_arrive_time_s']['today'])){
                        $expectArriveTime = strtotime(date('Y-m-d', strtotime('+1day')).' '.$tParam[$k]['self_lifting_time']['other'][0]);
                    }

                }elseif ($tParam[$k]['expense_type'] == 2 ){
                    $expectArriveTime = time() + ($expectTakeTime + $robExpectTime) * 60;
                    if(empty($tParam[$k]['self_lifting_time']['today'])){
                        $expectArriveTime = strtotime(date('Y-m-d', strtotime('+1day')).' '.$tParam[$k]['self_lifting_time']['other'][0]);
                    }
                }
            }

			$tData[] = array(
					'merchant_id'=>$k,
					'consumer_id'=>$this->userId,
					'code'=>$code,
					'pay_code'=>$payCode,
					'type'=>isset($tMerchant[$k]['category_id'])?$tMerchant[$k]['category_id']:'0',//类型
					'expense_type'=>$tParam[$k]['expense_type'],//商家消费类型
					'pay_type'=>$reality_amount>0 ? 0:1,
					'pay_time'=>$reality_amount>0 ? '':time(),
					'product_amount'=>$v['product_amount'],//商品的价格
					'total_amount'=>$total_amount,
					'reality_amount'=>$reality_amount,//下单前实际支付金额
			        'remark'=>$tParam[$k]['remark'],
					'status'=>$reality_amount>0 ? 1:2,//待支付
					'contacts'=>$contacts,
					'gender'=>$gender,
					'mobile'=>$mobile,
					'address'=>$address,
					'latitude'=>$latitude,
					'longitude'=>$longitude,
					'province_id'=>$province_id,
					'city_id'=>$city_id,
					'county_id'=>$county_id,
					'shipping_fee'=>$shipping_fee,
					'percent'=>$web_percent,//类型
                    'bonus'=>$bonus,
                    'lunch_box_fee'=>$tParam[$k]['lunch_box_fee'],
                    'postal_card'=>$postalCard ,
                    'merchant_discount'=> sprintf("%.2f", $fullcut['money'] + $firstOrder + $coupon),
					'param'=>json_encode(array(
							'coupon'=>$coupon,
							'bonus'=>$bonus,
                            'postal_card'=>$postalCard,
							'full_cut'=>$fullcut['money'],
							'first_order_reduce'=>$firstOrder,
                            'lunch_box_fee'=>$tParam[$k]['lunch_box_fee'],
						)),
					'addtime'=>time(),

                    //新增字段
                    'deliveryman_income' => $deliverymanIncome,
                    'merchant_income' => $merchantIncome,
                    'web_income' => $webIncome,
                    'after_sale'=>1,//未申请
                    'is_comment'=>1,//未评价
                    'shipping_type'=>$tMerchant[$k]['shipping_type'],//配送模式 根据该商家来设置的
                    'shortage_handing'=>json_encode($tParam[$k]['shortage_handing']),//{"value":"s1","remark":"备注信息"}
			        'expect_arrive_time'=> $expectArriveTime,
			);
			//计算总金额
			$total = $total + $reality_amount;
		}
		
		$this->db->trans_begin();//开启事务
		
		if ( ! $tId = $this->mOrder->saveBatch($tData)){
			$this->db->trans_rollback();
			$this->appReturn(0,'下单失败');
		}
		
		/**--------------------------------------------------------------
		 * 组合 订单产品信息
		 */
		//获取订单id
		$tempOrder = $this->mOrder->getOrderByCodes($tempCode);
		if ( ! $tempOrder){
			$this->db->trans_rollback();
			$this->appReturn(0,'下单失败');
		}


		//组合订单产品信息
		foreach ($tOrder as $k=>$v){
			foreach ($v['list'] as $kk=>$vv){
                $price = empty($vv['variant_id'])?$vv['goods_price']:$vv['v_price'];
				$orderProduct[] = array(
						'order_id'=>$tempOrder[$k],//根据商户id 获取订单id
						'product_id'=>$vv['id'], //产品id
						'price'=>$price,
						'quantity'=>$vv['b_quantity'],
						'reality_amount'=> sprintf('%.2f',$price*$vv['b_quantity']),
						'variant_id'=>empty($vv['variant_id'])?"0":$vv['variant_id'],//变体序号
                        'tags'=>empty($vv['tags'])?"":$vv['tags'],//属性
				);
				
				/**
				 * 处理商品变体(核销，送达增加销量)
				 */
//				$sale_quantity[$vv['id']] = (isset($sale_quantity[$vv['id']]) ? $sale_quantity[$vv['id']] : 0 )+ 1;
//				if ( ! $this->mProduct->savePropertyVariant(array('sale_quantity'=>$vv['sale_quantity'] + 1),$vv['id'],$vv['variant_id'])){
//					$this->db->trans_rollback();
//					$this->appReturn(0,'下单失败');
//				}
				#end
			}
		}
		

		//判断商品数量是否一致
		if (count($products) != count($orderProduct)){
			$this->db->trans_rollback();
			$this->appReturn(0,'下单失败');
		}
		
		//批量保存订单产品信息
		if ( ! $this->mOrder->saveOrderProduct($orderProduct)){
			$this->db->trans_rollback();
			$this->appReturn(0,'下单失败');
		}
		
		
		/**
		 * 下单成功后，处理红包，处理代金劵 处理购物车
		 */
		$this->loadModel('ConsumerPromotionModel', 'mPromotion','consumer');
		if ( ! $this->mPromotion->saveBatchBonusLog(array('status'=>2),$bBonusIds)){
			$this->db->trans_rollback();
			$this->appReturn(0,'下单失败');
		}
		
		if ( ! $this->mPromotion->saveBatchCouponLog(array('status'=>2),$bCouponIds)){
			$this->db->trans_rollback();
			$this->appReturn(0,'下单失败');
		}

		// 处理包邮卡
        if (!empty($postalCardIds) && !empty($tPostalCard)){
            $this->db->where_in('id', $postalCardIds);
            $query = $this->mPostalCard->update($this->mPostalCard->tbPostalCardLog,
                array(
                    'status'=>2,
                    'order_id' => $tempOrder[$tMerchantIds[0]],
                    'usedtime' => time()
                )
            );
            if ( !$query){
                $this->db->trans_rollback();
                $this->appReturn(0,'下单失败');
            }
        }

		/**
		 * 删除购物车
		 */
		foreach ($products as $k=>$v){
			
			//循环删除该消费者 购物车中的该商品
			$this->db->where(array(
					'consumer_id'=>$this->userId,
					'product_id'=>$v['product_id'],
					'variant_id'=>$v['sort'],
			));
			
			if ( ! $this->mCart->delete($this->mCart->tbShoppingCart)){
				$this->db->trans_rollback();
				$this->appReturn(0,'下单失败');
			}
		}
		
		//订单下单时 减少库存
		$this->loadModel('AdmSettingModel', 'mSet','admin');
		$reduce_stock = $this->mSet->get('reduce_stock');
		
		if ($reduce_stock == 1){
			//下单时减少
			foreach ($tOrder as $k=>$v){
				$result = $this->mOrder->reduceStocks($tempOrder[$k]);
				if($result['status'] == 0){
                    $this->db->trans_rollback();
                    $this->appReturn(0, $result['message']);
                }
			}
		}
		
		/**
		 * 增加销量（送达（核销）后增加销量）
		 */
//		foreach ($sale_quantity as $productId => $quantity){
//			if ( ! $this->mProduct->save(array('sale_quantity'=>$quantity),$productId)){
//				$this->db->trans_rollback();
//				$this->appReturn(0,'下单失败[ERROR:1001]');
//			}
//		}
		
		/**
		 * 获取支付参数
		 */
		$tData = array(
				'code'=>json_encode($tempCode),//预支付订单
				'total_amount'=>sprintf('%.2f',$total),
		);
		
		$this->db->trans_commit();
		$this->appReturn(1,'订单提交成功',$tData);
	}


    /**
     * 验证收货地址以及经纬度
     * @param string $sendAddress      起始配送地址
     * @param string $latitude         起始纬度
     * @param string $longitude        起始经度
     * @param string $sendToDddress    配送到达地址
     * @param string $sendToLatitude   配送到达纬度
     * @param string $sendToLongitude 配送到达经度
     * @param int $fee  所花费运费
     * @return array
     */
    /*
	private function checkCoordinates($sendAddress,$latitude,$longitude,$sendToDddress,$sendToLatitude,$sendToLongitude,$fee){

        get_instance()->loadModel('AdmSettingModel', 'mSett', 'admin');
        $config = $this->mSett->get('map_key as ak,base_distribution_fee,base_distribution_distance,base_distribution_weight
				,exceed_base_distance,exceed_base_weight,rob_expect_time,exceed_base_distance_number,exceed_base_weight_number', 'deliveryman');
        $url = 'http://api.map.baidu.com/geocoder/v2/?address='.$sendAddress.'&output=json&ak='.$config['ak'];

        $tA = $this->_request($url);

        if($tA == false){
            return ['status' => 0, 'message' => '地址解析错误'];
        }

        $tS = dsitance($latitude, $longitude, $tA[0], $tA[1]);
        if( ! is_numeric($tS) || $tS > 100){
            return ['status' => 0, 'message' => '店铺地址有误差'];
        }

        $url = 'http://api.map.baidu.com/geocoder/v2/?address='.$sendToDddress.'&output=json&ak='.$config['ak'];
        $tA = $this->_request($url);

        if($tA == false){
            return ['status' => 0, 'message' => '地址解析错误'];
        }

		$tS = dsitance($sendToLatitude, $sendToLongitude, $tA[0], $tA[1]);

		if( ! is_numeric($tS) || $tS > 100){
			return ['status' => 0, 'message' => '送货地址有误差'];
		}

		$distance = dsitance($latitude, $longitude, $sendToLatitude, $sendToLongitude);

		$tIncome = $this->getIncome($distance / 1000, 0, $config);

		if($tIncome != $fee){
			return ['status' => 0, 'message' => '配送费发生了变化，请重新下单'];
		}
		return ['status' => 1, 'message' => ''];
    }*/


	/**
	 * 获取店铺首单减免金额
	 * @param array $merchantIds 商家ids数组
	 * @return array 商家为键的数组 ["1"=>10]
	 */
	private function _firstOrder($merchantIds){
        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');
        //获取店铺订单数量
        $tA = $this->mOrder->firstOrderByMerchantId($merchantIds, $this->userId);

        $data = array();
        foreach ($tA as $v){
            if($v['count'] == 0 && $v['first_order_reduce'] > 0){
                $data[$v['merchant_id']] = $v['first_order_reduce'];
            }
        }

        return $data;
	}
	
	/**
	 * 从实际订单产品中，获取商家的运费
	 * @param unknown $tProduct
	 * @param unknown $products
	 * @param unknown $address_id
	 * @return array|number|unknown
	 * @author zyl
	 */
	private function _orderFee($tProduct, $products, $address_id){
	   
		/**
		 * 根据当前地址获取邮费
		 */
		$tShipping = array();
		if ($address_id){
			$tShipping = $this->shippingFee($products,$address_id);
		}

		//由于没有包邮不包邮的模式
        return $tShipping;
		/**---------------------------------------------
		 * 多商品运费筛选
		 * 备注：逻辑为，如果该商家的商品中，有一个为包邮，则不需要在寻找邮费。如果不是就赋值运费，运费的来源是商品的总质量+地区计算得来
		 */
       
		$tmAmount = array();

        foreach ($tShipping as $kk=>$vv){
            //寻找运费
            $tmAmount[$vv['merchant_id']] = $vv;//设置配送费
        }

        foreach ($tProduct as $k=>$v){
			//判断之前
            if ($v['is_free_shipping'] == 2){
                //包邮
                $tmAmount[$v['merchant_id']]['shipping_fee'] = 0;//配送费0
            }
		}
		
		return $tmAmount;
	}
	/**
	 * 获取我的订单
	 */
	public function getOrderList(){
		//表单验证
		$vConf = array(
				array('type', '类型', 'required|in_list[1,2]'),//1-配送 2-到店
// 				array('status', '状态', ''),
				array('page', '分页', 'required|is_natural_no_zero'),
		);
		$this->formDataValidation($vConf);
		
		$type = post('type');
		$status = post('status');
		$page = post('page');
		
		//加载模型
		$this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');
		$this->loadModel('MerchantUserModel', 'mMerchant', 'merchant');
		
		//验证
		if ( $status && ! array_key_exists($status, $this->mOrder->STATUS)){
			$this->appReturn(0,'订单状态不存在');
		}
		
		/**
		 * 获取订单列表
		 * @var Ambiguous $tA
		 */
		$tA = $this->mOrder->appGetList($this->userId, $type, $status,$page, $this->port);
		if ( ! $tA){
			$this->appReturn(1,'订单空空的');
		}
		
		/**
		 * 获取订单商家信息
		 */
		$tMerchant = array();
		$tOrder = array();
		
		$tMerchantIds = array();
		$tOrderIds = array();
        $dlmOrderIds = array();//平台配送
		foreach ($tA as $k=>$v){
			if (! in_array($v['merchant_id'], $tMerchantIds)){
				$tMerchantIds[] = $v['merchant_id'];
			}
			if (! in_array($v['id'], $tOrderIds)){
				$tOrderIds[] = $v['id'];
			}
			//平台配送
            if ($v['shipping_type'] == 2 && ! in_array($v['id'], $dlmOrderIds)){
                $dlmOrderIds[] = $v['id'];
            }
		}
		
		if( ! $tMerchantIds || ! $tOrderIds){
			$this->appReturn(0,'获取信息失败');
		}
		
		/**
		 * 获取订单信息
		 * @var array $tOrderProduct
		 */
		$tOrderProduct = $this->mOrder->getOrderProductInfoByIds(array(),$tOrderIds);
		if( ! $tOrderProduct){
			$this->appReturn(0,'获取信息失败');
		}

        /**
         * 获取配送员信息
         */
        $deliveryman = array();
        if($dlmOrderIds){
            $this->loadModel('DlnOrderModel', 'mDln', 'deliveryman');
            $deliveryman = $this->mDln->getDeliverymanInfoByOrderIds($dlmOrderIds);
        }
		/**
		 * 获取商家信息
		 */
		$tMerchant = $this->mMerchant->getInfoByIds($tMerchantIds);
		if( ! $tMerchant){
			$this->appReturn(0,'商家信息失败');
		}
		
		/**
		 * 订单数据
		 */
		foreach ($tA as $k=>$v){
			$tA[$k]['shop_name'] = isset($tMerchant[$v['merchant_id']]['shop_name'])?$tMerchant[$v['merchant_id']]['shop_name']:'暂无';
			$tA[$k]['portrait'] = isset($tMerchant[$v['merchant_id']])?$tMerchant[$v['merchant_id']]['portrait']['xs']:'暂无';
			$tA[$k]['title'] = isset($tOrderProduct[$v['id']]) ? $tOrderProduct[$v['id']][0]['name']:'暂无';
			
			//如果字符串大于10 则省略
			if (strlen($tA[$k]['title'])>10){
				$tA[$k]['title'] = mb_substr($tA[$k]['title'],0,10).'..等'.count($tOrderProduct[$v['id']]).'件商品';
			}else{
				$tA[$k]['title'] = $tA[$k]['title'].'等'.(isset($tOrderProduct[$v['id']])?count($tOrderProduct[$v['id']]):"0").'件商品';
			}
			
			$tA[$k]['count'] = isset($tOrderProduct[$v['id']])?count($tOrderProduct[$v['id']]):"0";
			//配送员信息
            $tInfo = isset($deliveryman[$v['id']])?$deliveryman[$v['id']]:array();
            $tA[$k]['delivery_name'] = '';
            $tA[$k]['delivery_portrait'] = '';
            if($tInfo){
                $tA[$k]['delivery_name'] = $tInfo['name'];
                $tA[$k]['delivery_portrait'] = $tInfo['portrait'];
            }
		}
		
		$this->appReturn(1,'',$tA);
	}

	/**
	 * 订单立即收货
	 */
	public function orderReceive(){
        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');

        //表单验证
		$vConf = array(
				array('order_id', '订单id', 'required'),
		);
		$this->formDataValidation($vConf);
		
		$orderId = post('order_id');

		$tA = $this->mOrder->getInfo($orderId,$this->userId, 0, true);
		if ( ! $tA){
			$this->appReturn(0,'订单不存在');
		}
		
		//是否待收货
		if ($tA['status'] != 3){
			$this->appReturn(0,'该订单无法确认收货');
		}

        $this->db->trans_begin();

        $result = $this->mOrder->_confirmReceipt($orderId,'立即收货',$tA['merchant_id'], $this->port, $this->userId);

		if ($result['status'] == 0){
            $this->db->trans_rollback();
			$this->appReturn(0, $result['message']);
		}
        //用户推送消息
        $msgData = array(
            'title' => '订单已收货',
            'content' => '您的订单已签收',
            'addtime' => time(),
        );
        $this->loadModel('ConsumerMessageModel', 'mMsg', 'consumer');
        if(!($this->mMsg->save($msgData, 0, $orderId))){
            $this->db->trans_rollback();
            $this->ajaxReturn(0, '消息保存失败');
        }
        //获取消息id
        $msgInfo = $this->mMsg->getInfo(0, 0, 0, $orderId);
        //删除消息查看记录
        $this->mMsg->deleteView($this->userId, $msgInfo['id']);
        jpush($msgData['title'], $msgData['content'], 1, array($tA['jpush_code']), 3, $orderId, $tA['expense_type']);

        //商家推送消息
        $merMsg = array(
            'title' => '订单已收货',
            'content' => '订单已被用户签收',
            'addtime' => time(),
        );
        $this->loadModel('merchantMessageModel', 'mMerMsg', 'merchant');
        if(!($this->mMerMsg->save($merMsg, 0, $orderId))){
            $this->db->trans_rollback();
            $this->ajaxReturn(0, '消息保存失败');
        }
        //获取消息id
        $msgIn = $this->mMerMsg->getInfo(0, $tA['merchant_id'], $orderId);
        //删除消息查看记录
        $this->mMerMsg->deleteView($tA['merchant_id'], $msgIn['id']);
        MerchantJpush($merMsg['title'], $merMsg['content'], 1, array($tA['merchant_jpush_code']), 3, $orderId);

        $this->db->trans_commit();
		$this->appReturn(1,'确认收货成功');
	}
	
	/**
	 * 立即支付
	 */
	public function orderPay(){
		//表单验证
		$vConf = array(
				array('code', '订单号', 'required'),
		);
		$this->formDataValidation($vConf);
		
		$code = post('code');
		
		//如果解析成功
		$arrayCode = is_numeric($code)? $code:json_decode($code,true);

		//加载模型
		$this->loadModel('ConsumerOrderModel', 'mOrder','consumer');
		$this->loadModel('ConsumerPayModel', 'mPay', 'consumer');
		
		$amount = 0;
		$tempCode = array();
		if (is_array($arrayCode)){
			$tOrders = $this->mOrder->getInfoByCodes($arrayCode);
			if ( ! $tOrders){
				$this->appReturn(0,'订单不存在');
			}
			
			foreach ($tOrders as $k=>$v){
				if ($v['status'] != 1){
					//待支付
					$this->appReturn(0,'订单已经被取消');
				}
				$tempCode[] = $v['code'];
				$amount += $v['reality_amount'];
			}
		}else{
			
			$tOrder = $this->mOrder->getInfoByCode($code, 0,$this->userId);
			if ( ! $tOrder){
				$this->appReturn(0,'订单不存在');
			}
			if ($tOrder['status'] != 1){
				//待支付
				$this->appReturn(0,'订单已经被取消');
			}
			
			$tempCode[] = $tOrder['code'];
			$amount = $tOrder['reality_amount'];
		}
		
		/**
		 * 创建预支付订单
		 */
		$this->db->trans_begin();//事务
		
		$payCode = getOrderCode();
		$data = array(
				'consumer_id'=>$this->userId,
				'code'=>$payCode,
				'amount'=>$amount,
				'type'=>2,//充值
				'pay_type'=>0, //没有支付方式
				'status'=>1,//未支付
				'param'=>json_encode($tempCode),
				'addtime'=>time(),
		);
		
		if ( ! $this->mPay->savePayOrder($data)){
			$this->db->trans_rollback();
			$this->appReturn(0,'调起支付失败[ERROR:01]');//预支付订单失败
		}
		
		/**
		 * 更新订单预支付订单号
		 */
		if ( ! $this->mOrder->saveBatch(array('pay_code'=>$payCode),0,$tempCode)){
			$this->db->trans_rollback();
			$this->appReturn(0,'调起支付失败[ERROR:02]');
		}

		/**
		 * 获取支付参数
		 */
		$tA['balance'] = $this->userBalance;
		$tA['code'] = $payCode;
		$tA['amount'] = $amount;
		//获取支付宝
		$tA['alipay'] = $this->mPay->_getAliPay($payCode,$amount);
		//获取微信支付
		$tA['wxpay'] = $this->mPay->_getWxPay($payCode,$amount);
		
		$this->db->trans_commit();
		$this->appReturn(1,'',$tA);
	}
	
	/**
	 * 取消订单
	 */
	public function orderCancel(){
		//表单验证
		$vConf = array(
				array('order_id', '订单id', 'required'),
		);
		$this->formDataValidation($vConf);
		
		$orderId = post('order_id');
		$this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');
		
		$tA = $this->mOrder->getInfo($orderId,$this->userId);
		if ( ! $tA){
			$this->appReturn(0,'订单不存在');
		}
		$status = 7;
		//是否待支付
		if ($tA['status'] != 1 && $tA['status'] != 2){
			$this->appReturn(0,'该订单无法取消');
		}

		$this->db->trans_begin();
		if($tA['status'] == 2){
		    //商家未接单前 取消已支付订单 原路退款
            $result = $this->mOrder->_OrderRefund($orderId, $this->userId,$tA['reality_amount'],$tA['pay_type'],
                                        $tA['wx_type'], $tA['pay_code'], $tA['code']);
            if($result['status'] == 0){
                $this->db->trans_rollback();
                $this->appReturn(0, $result['message']);
            }
            $status = 8;
        }
        //商品增加库存
        $this->loadModel('AdmSettingModel', 'mSet','admin');
        $reduce_stock = $this->mSet->get('reduce_stock');

        if ($reduce_stock == 1){
            //下单时减少
            $result = $this->mOrder->reduceStocks($orderId, true);
            if($result['status'] == 0){
                $this->db->trans_rollback();
                $this->appReturn(0, $result['message']);
            }
        }
		if ( ! $this->mOrder->save(array('status' => $status),0,$orderId)){
			$this->db->trans_rollback();
			$this->appReturn(0,'订单取消失败');
		}

        $rS = $this->mOrder->saveOrderLog($orderId, '交易关闭', '消费者取消了订单', $this->port, $this->userId);
        if (!$rS){
            $this->appReturn(0,'取消失败[ERROR:02]');
        }

        //如果使用包邮卡 退回
        if($tA['postal_card'] > 0){
            $this->loadModel('ConsumerPostalCardModel', 'mPostalCard','consumer');

            $this->db->where('order_id', $orderId);
            $query = $this->mPostalCard->update($this->mPostalCard->tbPostalCardLog,
                array(
                    'status' => 1,
                    'order_id' => 0,
                    'usedtime' => ''
                )
            );
            if ( !$query){
                $this->db->trans_rollback();
                $this->appReturn(0,'包邮卡退还失败');
            }
        }
		$this->db->trans_commit();
		$this->appReturn(1,'取消成功');
	}
	
	/**
	 * 删除订单
	 */
	public function orderRemove(){
		//表单验证
		$vConf = array(
				array('order_id', '订单id', 'required'),
		);
		$this->formDataValidation($vConf);
		
		$orderId = post('order_id');
		$this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');
		$this->loadModel('ConsumerMessageModel', 'mMessage', 'consumer');

		$tA = $this->mOrder->getInfo($orderId,$this->userId);
		if ( ! $tA){
			$this->appReturn(0,'订单不存在');
		}
		
		//是否待支付 7-取消  5-完成 才能删除
		if ( ! in_array($tA['status'], [1,5,6,7])){
			$this->appReturn(0,'该订单无法删除');
		}
		
		$this->db->trans_begin();
		if ($tA['status'] == 7){
			//真删除订单
			$this->db->where('id',$orderId);
			if ( ! $this->db->delete($this->mOrder->tbOrder)){
				$this->db->trans_rollback();
				$this->appReturn(0,'删除订单失败[ERROR:01]');
			}
			
			//删除订单产品
			$this->db->where('order_id',$orderId);
			if ( ! $this->db->delete($this->mOrder->tbOrderProduct)){
				$this->db->trans_rollback();
				$this->appReturn(0,'删除订单失败[ERROR:02]');
			}
			// 删除产品操作记录
            $rS = $this->mOrder->deleteOrderLog($orderId);
            if (!$rS){
                $this->db->trans_rollback();
                $this->ajaxReturn(0, '删除订单失败[ERROR:03]');
            }

            //删除消息记录
            $this->mMessage->deleteMsg($orderId, $this->userId);

		}elseif (in_array($tA['status'], [5,6])){
			//订单完成的 假删除
			
			if ( ! $this->mOrder->save(array('is_consumer_delete'=>2),0,$orderId)){
				$this->db->trans_rollback();
				$this->appReturn(0,'订单删除失败');
			}
            $rS = $this->mOrder->saveOrderLog($orderId, '删除订单', '消费者删除了完成的订单', $this->port, $this->userId);
            if (!$rS){
                $this->appReturn(0,'取消失败[ERROR:02]');
            }

		}

		$this->db->trans_commit();
		$this->appReturn(1,'删除成功');
	}
	
	/**
	 * 获取订单跟踪信息
	 */
	public function orderTracking(){
        $this->loadModel('AdmSettingModel', 'mSett', 'admin');
        //表单验证
        $vConf = array(
            array('order_id', '订单id', 'required'),
        );
        $this->formDataValidation($vConf);

        $orderId = post('order_id');

        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');

        $tA = $this->mOrder->getInfo($orderId, $this->userId);
        if ( ! $tA){
            $this->appReturn(0, '订单不存在');
        }
        if(!in_array($tA['status'], array(3,4,5)) || $tA['shipping_type'] != 2){
            $this->appReturn(0, '暂无配送信息');
        }
        //配送信息
        $traces = array();
        //获取配送信息
        $this->loadModel('DlnOrderModel', 'mDlnOrder', 'deliveryman');
        $dlnOrder = $this->mDlnOrder->getDeliverymanInfoByOrderIds(array($orderId));
        $dlnOrder = $dlnOrder[$orderId];
        if($dlnOrder['status'] == 1){
            $traces[] = array('status' => '配送员'.$dlnOrder['status_str'],'time' => date('m-d H:i',time()));
        }elseif ($dlnOrder['status'] == 2){
            $traces[] = array('status' => '配送员'.$dlnOrder['status_str'],'time' => date('m-d H:i',time()));
            $traces[] = array('status' => '配送已接单','time' => $dlnOrder['addtime']);
        }
        elseif ($dlnOrder['status'] == 3){
            $traces[] = array('status' => '配送员'.$dlnOrder['status_str'],'time' => date('m-d H:i',time()));
            $traces[] = array('status' => '配送员已取单','time' => $dlnOrder['pickup_time']);
            $traces[] = array('status' => '配送员已接单','time' => $dlnOrder['addtime']);
        }elseif ($dlnOrder['status'] == 4){
            $traces[] = array('status' => '配送员已完成','time' => $dlnOrder['complete_time']);
            $traces[] = array('status' => '配送员已取单','time' => $dlnOrder['pickup_time']);
            $traces[] = array('status' => '配送员已接单','time' => $dlnOrder['addtime']);
        }
        $traces[] = array('status' => '商家已接单','time' => date('m-d H:i',$tA['merchant_take_time']));

        $ak = $this->mSett->get('map_key','deliveryman');

        $html = $this->view('order/shopper_details',[
                'ak'=>$ak,
                'delivery_latitude'=>$dlnOrder['status'] == 4?$tA['latitude']:$dlnOrder['latitude'],
                'delivery_longitude'=>$dlnOrder['status'] == 4?$tA['longitude']:$dlnOrder['longitude'],
                'shop_longitude'=>$tA['shop_longitude'],
                'shop_latitude'=>$tA['shop_latitude'],
                'send_to_latitude'=>$tA['latitude'],
                'send_to_longitude'=>$tA['longitude'],
                'Traces'=>$traces,
            ]
            ,0,0,0,true);

        $this->appReturn(1, '', $html);
	}
	
	/**
	 * 获取订单详情
	 */
	public function getOrderDetail(){
        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');

        //表单验证
		$vConf = array(
				array('order_id', '订单id', 'required'),
		);
		$this->formDataValidation($vConf);
		
		$orderId = post('order_id');

		$tA = $this->mOrder->appGetInfo($orderId,$this->userId, 0, '', $this->port);
		
		if ( ! $tA){
			$this->appReturn(0,'订单不存在');
		}
		if ($tA['shipping_type'] == 2){//平台配送
            $this->loadModel('DlnOrderModel', 'mDln', 'deliveryman');
            $deliveryman = $this->mDln->getDeliverymanInfoByOrderIds(array($orderId));
            $tInfo = isset($deliveryman[$orderId])?$deliveryman[$orderId]:array();
            if($tInfo){
                $tA['delivery']['delivery_name'] = $tInfo['name'];
                $tA['delivery']['delivery_mobile'] = $tInfo['mobile'];
                $tA['delivery']['delivery_portrait'] = $tInfo['portrait'];
                $tA['delivery']['delivery_status'] = $tInfo['status'];
            }
        }
		$tA['list'] = $this->mOrder->getOrderProductList($orderId);
		//缺货处理
		
		$tA['shortage_handing']['list'] = $this->mOrder->getShortage($tA['shortage_handing']['value']);
		
		$this->loadModel('ConsumerMessageModel', 'mMsg','consumer');
        $msgInfo = $this->mMsg->getInfo(0,$this->userId,0,$orderId);
        if ($msgInfo && $msgInfo['viewed'] == 1) {
            //阅读信息
            $data = array(
                'consumer_id'=> $this->userId,
                'message_id'=> $msgInfo['id'],
                'is_delete'=> 1,
                'order_id'=> $orderId,
                'addtime'=> time(),
            );
            if ( ! $this->mMsg->saveView($data)){
                //$this->appReturn(0,'获取失败');
            }
        }

		$this->appReturn(1,'',$tA);
	}

    /**
     * 催一下
     */
    public function push(){
        //表单验证
        $vConf = array(
            array('order_id', '订单id', 'required'),
        );
        $this->formDataValidation($vConf);

        $orderId = post('order_id');
        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');

        $tA = $this->mOrder->getInfo($orderId,$this->userId,0);
        if ( ! $tA){
            $this->appReturn(0,'订单不存在');
        }
        if($tA['last_push_time'] && time() - $tA['last_push_time'] < 5*60){
            $this->appReturn(0,'催单频繁，请稍后再试');
        }
        //更新催单时间
        if(!($this->mOrder->save(array('last_push_time' => time()), 0, $orderId))){
            $this->appReturn(0,'催单失败');
        };
        MerchantJpush('催单消息', '订单：'.$tA['code'].'已经等不及了，请尽快配送', 1, array($tA['merchant_jpush_code']), 3, $orderId);

        $this->appReturn(1, '催单成功');
    }

	/**
	 * 对订单商品进行评价
	 */
    public function saveComment(){
        //表单验证
        $vConf = array(
            array('order_id', '订单id', 'required|is_natural_no_zero'),
            array('product', '订单商品', 'required'),
//            array('service_tags', '服务评分标签', 'required'),
            array('service_score', '服务评分', 'required|is_natural_no_zero|in_list[1,2,3,4,5]'),
//            array('deliveryman_tags', '配送员评分标签', 'required'),
//            array('deliveryman_score', '配送员评分', 'is_natural_no_zero|in_list[1,2,3,4,5]'),
        );
        $this->formDataValidation($vConf);
        $orderId = post('order_id');
        $product = post('product');
        $serviceTags = post('service_tags'); // 菜好,肉多 多个以逗号隔开
        $serviceScore = (int)post('service_score'); // 服务评分
        $deliverymanTags = post('deliveryman_tags'); // 长得帅,跑得快 多个以逗号隔开
        $deliverymanScore = post('deliveryman_score'); // 配送员评分
        $product = json_decode($product, true);
        $serviceTags = json_decode($serviceTags, true);
        $deliverymanTags = json_decode($deliverymanTags, true);

        //加载模型
        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');
        $this->loadModel('MerchantUserModel', 'mMerchant', 'merchant');
        $this->loadModel('DlnOrderModel', 'mDOrder', 'deliveryman');
        $this->loadModel('DlnCommentModel', 'mDComment', 'deliveryman');

        //验证订单是否存在
        $tOrder = $this->mOrder->getInfo($orderId,$this->userId,0,true);
        if ( ! $tOrder){
            $this->appReturn(0,'订单不存在');
        }
        if($tOrder['status'] != 4){
            $this->appReturn(0,'该订单不能评论');
        }
        if($tOrder['is_comment'] == 2){
            $this->appReturn(0,'已经评论过');
        }
//        if($tOrder['expense_type'] == 1 && $tOrder['shipping_type'] == 2 && !$deliverymanTags){
////            $this->appReturn(0,'配送员评分标签必选');
//        }
        if($tOrder['expense_type'] == 1 && $tOrder['shipping_type'] == 2 && !$deliverymanScore){
            $deliverymanScore = 5;
//            $this->appReturn(0,'配送员评分必选');
        }
        //查看售后状态
        $tService = $this->mOrder->getServiceInfo(0, $orderId);
        if($tService &&$tService['status'] == 3){
            $this->appReturn(0,'该订单正在售后中~');
        }
        $orderProductId = array(); // 商品订单id
        if($product){
            foreach ($product as $k => $v){
                if(!isset($v['order_product_id'])){
                    $this->appReturn(0,'数据格式错误');
                }
                if (!in_array($v['order_product_id'], $orderProductId)){
                    $orderProductId[] = $v['order_product_id'];
                }else{
                    unset($product[$k]);
                }
            }
        }
        //验证该订单产品

        $tProduct = $this->mOrder->getOrderProductInfoByIds($orderProductId, $orderId, 0, true);
        if (count($orderProductId) != count($tProduct)){
            $this->appReturn(0,'商品订单数据错误');
        }

        $time = time();
        $data = array();
        foreach ($product as $k => $v) {
            //上传图片
            $imgPath = array();
            if (!empty($v['imgs'])) {
                if (count($v['imgs']) > 3){ // 只取前3个
                    $imgs = array_slice($v['imgs'], 0, 3);
                }else{
                    $imgs = $v['imgs'];
                }
                $tId = $orderId;
                $path = 'uploads/product/comment/' . $tId.'/';
                try {
                    $result = moveImage($imgs, $path);
                } catch (Exception $e) {
                    $this->appReturn(0, "图片异常" . $e->getMessage());
                }

                if (!empty($result)) {
                    foreach ($result as $kk => $vv) {
                        $imgPath[] = str_replace(base_url(), "", $vv);
                    }
                }
            }
            $data[] = array(
                'order_id' => $orderId,
                'product_id' => $tProduct[$v['order_product_id']]['product_id'],
                'order_product_id' => $v['order_product_id'],
                'consumer_id' => $this->userId,
                'merchant_id' => $tOrder['merchant_id'],
                'score' => (int)$v['score'],
                'service_score' => $serviceScore,
                'tags' => $serviceTags?','.implode(',', $serviceTags).',':'',
                'content' => $v['content'],
                'reply' => '',
                'imgs' => json_encode($imgPath),
                'admin_reply' => '',
                'addtime' => $time,
            );

        }

        //事务
        $this->db->trans_begin();
        $tRS = $this->mComment->save($data, 0, true);
        if (! $tRS){
            $this->db->trans_rollback();
            $this->appReturn(0,'保存失败');
        }

        // 更改订单状态/评论状态
        $oSave = $this->mOrder->save(array('status' => 5, 'is_comment' => 2), 0, $orderId);
        if ( ! $oSave){
            $this->db->trans_rollback();
            $this->appReturn(0,'保存失败');
        }

        //统计商家平均分
        $tAvgScore = $this->mComment->totalCommentScore($tOrder['merchant_id']);
        if ( ! $this->mMerchant->save(array('score'=>$tAvgScore),$tOrder['merchant_id'])){
            //平均分没有保存成功
        }

        //存在推荐人
        $parentInfo = [];
        if($tOrder['parent_id'] > 0){
            $this->loadModel('AdmSettingModel', 'mSetting', 'admin');
            $sharePercent = $this->mSetting->get('share_percent');
            if($sharePercent > 0){
                $balanceLog = [
                    'consumer_id' => $tOrder['parent_id'],
                    'type' => 7,
                    'pay_type' => 7,
                    'param' => $orderId,
                    'amount' => sprintf('%.2f', ($tOrder['reality_amount']*$sharePercent)/100),
                    'status' => 2,
                    'addtime' => time(),
                    'confirm_time' => time(),
                ];
                $parentInfo = $this->mUser->getInfo($tOrder['parent_id']);
                if ( ! $this->mUser->saveBuyLog($balanceLog)){
                    $this->db->trans_rollback();
                    $this->appReturn(0,'保存失败');
                }
                $cData[] = [
                    'id' => $tOrder['parent_id'],
                    'balance' => $parentInfo['balance'] + $balanceLog['amount'],
                ];

                $query = $this->mUser->updateBatch($this->mUser->tbUser, $cData, 'id');
                if ( ! $query){
                    $this->db->trans_rollback();
                    $this->appReturn(0,'分享数据保存失败');
                }
            }

            //首单 分享注册送红包
            $this->db->select('id,code')
                    ->where('status', 5)
                    ->where('consumer_id', $this->userId);
            $count = $this->mOrder->count($this->mOrder->tbOrder);

            if($count == 1 && $parentInfo){
                $this->loadModel('ConsumerPromotionModel', 'mPromotion', 'consumer');

                $this->db->select('id,name,type,money,surplus_number')
                    ->where(array('type' => 1,'status'=> 2,'surplus_number >' => 0,'send_start_time <='=> time(),'send_end_time >=' => time()));
                $bonusList = $this->mPromotion->getAll($this->mPromotion->tbBonus);
                if($bonusList){
                    $bA = array();
                    $else = array();
                    foreach ($bonusList as $v){
                        $bA[] = array(
                            'bonus_id' => $v['id'],
                            'type' => $v['type'],
                            'consumer_id' => $tOrder['parent_id'],
                            'money' => $v['money'],
                            'status' => 1,
                            'param' => $orderId,
                            'addtime' => time()
                        );
                        $else[] = array(
                            'id' => $v['id'],
                            'surplus_number' => $v['surplus_number'] - 1,
                        );
                    }
                    if(!($this->mPromotion->saveBonusLog($bA, 0, true))){
                        $this->db->trans_rollback();
                        $this->ajaxReturn(0, '红包赠送失败');
                    }
                    //更新剩余红包数量
                    if(!($this->mPromotion->save($else, 0, true))){
                        $this->db->trans_rollback();
                        $this->ajaxReturn(0, '红包赠送失败');
                    }
                }
            }

        }
        //送货上门 平台配送
        if($tOrder['shipping_type'] == 2 && $tOrder['expense_type'] == 1){
            // 获取配送员信息
            $dInfo = $this->mDOrder->getDeliverymanInfoByOrderIds(array($orderId));

            if (empty($dInfo)){
                $this->appReturn(0, '获取配送员信息失败');
            }

            // 配送员评价信息
            $dlnData = array(
                'order_id' => $orderId,
                'deliveryman_id' => $dInfo[$orderId]['deliveryman_id'],
                'tags' => $deliverymanTags?','.implode(',', $deliverymanTags).',':'',
                'score' => $deliverymanScore,
                'addtime' => $time
            );
            $dId = $this->mDComment->save($dlnData);
            if (!$dId){
                $this->db->trans_rollback();
                $this->appReturn(0,'保存失败');
            }
            //统计配送员平均分
            $tAvgScore = $this->mDComment->totalCommentScore($dInfo[$orderId]['deliveryman_id']);
            $this->mDComment->update($this->mDComment->tbUser, array('score' => $tAvgScore));

        }

        $this->db->trans_commit();
        $this->appReturn(1,'评论成功');
    }


	/**
	 * 申请售后服务
	 */
	public function saveService(){
		//表单验证
		$vConf = array(
            array('order_id', '订单id', 'required|is_natural_no_zero'),
            array('reason', '售后原因', 'required'),
            array('amount', '售后金额', 'required'),
		);
		$this->formDataValidation($vConf);
        $orderId = post('order_id');
		$remark = trim(post('remark'));
		$reason = trim(post('reason'));//售后原因
		$amount = trim(post('amount'));//售后金额
		
		//加载模型
		$this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');
		
		$tService = $this->mOrder->getServiceInfo(0,$orderId);
		if ( ! empty($tService) && in_array($tService['status'], array(2,3))){
			$this->appReturn(0,'请勿重复提交售后');
		}
		//验证订单是否存在
		$tOrder = $this->mOrder->getInfo($orderId,$this->userId);
		if ( ! $tOrder){
			$this->appReturn(0,'订单不存在');
		}
        if ($tOrder['status'] != 2 && $tOrder['status'] != 3 && $tOrder['status'] != 4){
            $this->appReturn(0, '不能申请售后');
        }
        //限制售后次数
        $serviceCount = $this->mOrder->hasOrderServiceCount($orderId, $this->userId);
        if($serviceCount >= 2){
            $this->appReturn(0, '已达申请售后次数上限，请联系平台');
        }
        if ($amount > $tOrder['reality_amount']){
            $this->appReturn(0, '退款金额不能大于'.$tOrder['reality_amount'].'元');
        }
        // 修改商品售后状态
        $this->db->trans_begin();
        $op = $this->mOrder->save(array('after_sale' => 2), 0, $orderId);
        if (!$op){
            $this->db->trans_rollback();
            $this->ajaxReturn(0, '保存失败');
        }
        //保存图片
        $imgPath = array();
        if ( ! empty($_FILES)){
            $path = 'uploads/product/service/'.$orderId;
            $addNum = 0;
            foreach ($_FILES as $k=>$v){
                if ($addNum > 3){
                    //默认上传5张
                    break;
                }
                $tRes = imageUpload($path, $k,uniqid().rand(0,999).rand(0,999),true);
                if ( ! $tRes['status']){
                    foreach ($imgPath as $kk => $vv){
                        if (file_exists($vv)){
                            unlink($vv);
                        }
                    }
                    $this->db->trans_rollback();
                    $this->appReturn(0,'上传失败');
                }
                $imgPath[] = $tRes['data'];
                $addNum ++;
            }

        }

        /**
         * 数据
         * @var array $data
         */
        $service_code = getOrderCode();
        $data = array(
            'merchant_id'=>$tOrder['merchant_id'],
            'consumer_id'=>$this->userId,
            'code'=>$service_code,
            'order_id'=>$orderId,
            'refund_amount'=>$amount,
            'remark'=>$remark,
            'reason'=>$reason,
            'pic'=>json_encode($imgPath),
            'order_status' => $tOrder['status'],
            'status'=>3,
            'addtime'=>time(),
        );

        if ( !$tSId = $this->mOrder->saveService($data)){
            $this->db->trans_rollback();
            $this->appReturn(0,'申请失败');
        }

        $this->loadModel('MerchantMessageModel', 'mMerMsg','merchant');
		$this->loadModel('MerchantUserModel', 'mMerchant','merchant');
		
		$tMerchant = $this->mMerchant->getMiniInfo($tOrder['merchant_id']);
		
		//给商家的推送消息
		$title = '您有一条售后订单';//商家消息标题
		$merMsg = array(
				'merchant_id'=>$tOrder['merchant_id'],
				'type'=>4,
				'order_id'=>$tSId,
				'title'=>$title,
				'content'=>'消费者于'.date('Y/m/d H:i:s').'对订单商品申请售后服务！请及时前往处理',
				'addtime'=>time(),
		);
		
		//保存商家消息
		if ( ! $msgId = $this->mMerMsg->save($merMsg)){
			$this->db->trans_rollback();
			$this->appReturn(0,'保存失败');
		}
        // 添加操作记录
        $rS = $this->mOrder->saveOrderLog($orderId, $tOrder['status_str'], "消费者申请售后",$this->port, $this->userId);
        if (!$rS){
            $this->db->trans_rollback();
            $this->ajaxReturn(0, '保存失败');
        }
        $this->db->trans_commit();
		//通知商家
		MerchantJpush($title,$title,4, $tMerchant['jpush_code'],4, $tSId);
		$this->appReturn(1,'申请成功');
	}

	/**
	 * 获取售后服务列表
	 */
	public function getServiceList(){
		//表单验证
 		$vConf = array(
				array('page', '分页', 'required|is_natural_no_zero'),
		);
		$this->formDataValidation($vConf); 
		
		$page = post('page');
		$status = post('status');
		
		//加载模型
		$this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');
		
		$tA = $this->mOrder->appGetServiceList($this->userId, 0, $page, $status);
//        p($tA);
		if ( ! $tA){
			$this->appReturn(1,'没有售后订单');
		}
		
		$tMid = array();//商家的ids
		foreach ($tA as $k=>$v){
			if ( ! in_array($v['merchant_id'], $tMid)){
				$tMid[] = $v['merchant_id'];
			}
		}
		
		$this->loadModel('MerchantUserModel', 'mMerchant', 'merchant');
		$tMerchant = $this->mMerchant->getInfoByIds($tMid);

		$this->loadModel('AdmSettingModel', 'mSetting', 'admin');
		$service_tel = $this->mSetting->get('web_service_tel');

		/**
		 * 组合数据
		 */
		foreach ($tA as $k=>$v){
			$tA[$k]['service_tel'] = HASSET($service_tel,"暂无平台电话");
			$tA[$k]['store_tel'] = HASSET($tMerchant[$v['merchant_id']]['store_tel'],"暂无商家电话");
		}

		$this->appReturn(1,'',$tA);
	}
	
	/**
	 * 获取售后服务详情
	 */
	public function getServiceDetail(){
		//表单验证
		$vConf = array(
				array('service_id', '售后id', 'required|is_natural_no_zero'),
		);
 		$this->formDataValidation($vConf);
		
//		$code = post('code');
		$serviceId = post('service_id');//售后id
		
		//加载模型
		$this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');

        $tA = $this->mOrder->getServiceInfo(0,  0, 0, $this->userId, 0, $serviceId);
		if ( ! $tA){
			$this->appReturn(0,'数据为空');
		}

		$product = $this->mOrder->getProductList(0,  $serviceId, $this->userId);
		if ( ! $product){
			$this->appReturn(0,'数据为空');
		}
		$this->loadModel('MerchantUserModel', 'mMerchant', 'merchant');
		$tShop = $this->mMerchant->getShopInfo($tA['merchant_id']);
		
		$tA['base'] = array(
            'code'=>$tA['code'],
            'order_code'=>$tA['order_code'],
            'addtime'=>$tA['addtime'],
		);
		
		$this->loadModel('AdmSettingModel', 'mSetting', 'admin');
		$service_tel = $this->mSetting->get('web_service_tel');
		
		$tA['shop'] = array(
				'shop_name'=>isset($tShop['shop_name'])?$tShop['shop_name']:'商家名称',
				'portrait'=>isset($tShop['portrait'])?$tShop['portrait']:getDefaultImg(),
				'address'=>$tShop['address_desc'],
				'store_tel'=>isset($tShop['store_tel'])?$tShop['store_tel']:'暂无电话',
				'service_tel'=>$service_tel,
				'longitude'=>isset($tShop['longitude'])?$tShop['longitude']:'0',
				'latitude'=>isset($tShop['latitude'])?$tShop['latitude']:'0',
				'easemob_merchant_code' => $tShop['jpush_code'],
		);

        foreach ($product as $k => $v){
            $tA['product'][$k] = $v;
        }

		$tA['service'] = array(
				'reason'=>$tA['reason'],
				'remark'=>$tA['remark'],
				'complete_remark'=>$tA['complete_remark'],
				'complete_time'=>$tA['complete_time'],
		);
		
		$this->loadModel('ConsumerMessageModel', 'mMsg','consumer');
        //改变消息状态
        $message = $this->mMsg->getInfo(0, $this->userId, $tA['id']);
        if ($message){
            // 添加消息查看记录
            if ($message['viewed'] == 1) {
                $messageData = array(
                    'consumer_id' => $this->userId,
                    'message_id' => $message['id'],
                    'is_delete' => 0,
                    'addtime' => time(),
                );

                if ( ! $this->mMsg->saveStatus($messageData)){
                    $this->ajaxReturn(0, '添加消息查看记录失败');
                }

            }
        }
		unset($product,$tA['reason'],$tA['remark'],$tA['complete_remark'],$tA['complete_time'],$tA['status_format_str'],
        $tA['consumer_id'],$tA['pay_type'],$tA['platform_remark'],$tA['order_status'],$tA['jpush_code']);
		$this->appReturn(1,'',$tA);
	}
	

    /**
     * 配送费计算
     * @param int $shipping_id  配送方式id
     * @param $weight    重量
     * @param $province   省
     * @param $city      市
     * @param $county    区县
     * @return int
     */
	private  function shippingFreight($shipping_id = 3,$weight,$province,$city,$county){
        $this->loadModel('AdmShippingModel', 'mShipping','admin');
        
        if($weight == 0) return 0; // 商品没有重量
        if($shipping_id == '') return 0;

        //查找配送区域
        $config = '';

        $tA = $this->mShipping->getAllShippingArea($shipping_id);
        foreach ($tA as $k=>$v){
            $regionId = json_decode($v['region_config'], true);
            if($config == '' &&  in_array($county,$regionId)){
                $config = $v['config'];
            }

            if($config == '' && in_array($city,$regionId)){
                $config = $v['config'];
            }

            if($config == '' && in_array($province,$regionId)){
                $config = $v['config'];
            }
        }

        if(!$config){
            return 0;
        }

        $config = json_decode($config, true);

        // 1000 克以内的 只算个首重费
        if($weight < 1000)
        {
            return $config['money'];
        }
        // 超过 1000 克的计算方法
        $weight = $weight - 1000; // 续重
       
        $freight = $config['money'] +  $weight * $config['add_money']; // 首重 + 续重 * 续重费

        return $freight;
    }
    
    /**
     * 跟换地址获取邮费
     */
    public function getShippingFee(){
    	//表单验证
    	$vConf = array(
    			array('product', '产品参数', 'required'),
    			array('address_id', '地址id', 'required'),
    	);
    	$this->formDataValidation($vConf);  
    	
    	$product = json_decode(post('product'),true);
    	$address_id = post('address_id');
    	
    	//验证产品格式
    	$tProduct = $this->mProduct->canAddOrder($this->userId, $product);
    	if ( ! is_array($tProduct)){
    		$this->appReturn(0,(is_string($tProduct) ? $tProduct : '格式错误'));
    	}
    	//---------------------------------------------
//     	$param = '[{"product_id":"43","sort":"0","quantity":"2"},{"product_id":"45","sort":"1","quantity":"2"},{"product_id":"45","sort":"2","quantity":"2"}]';
//     	$this->userId = 23;
//     	$product = json_decode($param,true);
//     	$address_id = 7;
    	//---------------------------------------------
    	$tData = $this->_orderFee($tProduct,$product,$address_id);
    	$tData = array_values($tData);
    	$this->appReturn(1,'',$tData);
    }

    /**
     * 根据所选地址，获取运费
     * @param array $productIds
     * @param number $addressId
     */
    private function shippingFee($product = array(),$address_id= 0){
    	
    	//加载模型
    	$this->loadModel('ConsumerAddressModel', 'mAddress','consumer');
//    	$this->loadModel('ConsumerProductModel', 'mProduct','consumer');
    	$this->loadModel('DlnOrderModel', 'mDln','deliveryman');
    	$this->loadModel('MerchantUserModel', 'mMerchant','merchant');
        $this->loadModel('AdmSettingModel', 'mSett', 'admin');

        //验证产品格式
    	$tProduct = $this->mProduct->canAddOrder($this->userId, $product);
    	if ( ! is_array($tProduct)){
    		$this->appReturn(0,(is_string($tProduct) ? $tProduct : '格式错误'));
    	}

    	//获取用户地址所在地
    	$tAddress = $this->mAddress->getInfo($address_id,$this->userId);
    	if ( ! $tAddress){
    		$this->appReturn(0,'地址不存在');
    	}
    	

    	//获取商家商品重量
    	$tWeight = array();
    	$totalWeight = 0;//单商家
    	foreach ($tProduct as $k=>$v){
    		if ( ! isset($tWeight[$v['merchant_id']])){
    			$tWeight[$v['merchant_id']] = 0;
    		}
    		if($v['v_weight'] > 0){
                $v['weight'] = $v['v_weight'];
            }
            $totalWeight += $v['weight'] * $v['b_quantity'];
    		$tWeight[$v['merchant_id']] += $v['weight'] * $v['b_quantity'];//单个重量 * 数量 获得总重量
    	}

        $tMid = array();
        foreach ($tProduct as $k=>$v){
            if ( ! in_array($v['merchant_id'],$tMid) ){
                $tMid[] = $v['merchant_id'];
            }
        }

        //获取商家
//        $merchant_distance_limit = $this->mSett->get('merchant_distance_limit');

        $tMerchants = $this->mMerchant->getInfoByIds($tMid);
    	foreach ($tMerchants as $k=>$v){
    		if ( isset($tMerchants[$k]['distance']) ){
    		    //如果计算过距离则直接下个
                continue;
    		}
            //计算距离(米)
            $distance =  getDistance($v['latitude'], $v['longitude'], $tAddress['latitude'], $tAddress['longitude']);
//            if($distance > $merchant_distance_limit*1000){
//                $this->appReturn(0,'不在商家配送范围内~');
//            }
            $tMerchants[$k]['distance'] = $distance>0?$distance:0;
    	}



        $config = $this->mSett->get('base_distribution_fee,base_distribution_distance,exceed_base_distance,
                                    exceed_base_distance_number,base_distribution_weight,exceed_base_weight,
                                    exceed_base_weight_number','deliveryman');

    	//运费数据
    	$tData = array();
    	foreach ($tMerchants as $kk => $vv){
    	    
    	    $expect = (($vv['distance'] / 1000) - $config['base_distribution_distance']);//超出距离 km
    	   if($expect <= 0){
    	       $expect = 0;
           }
            $distance_amount = 0;
           if($config['exceed_base_distance_number'] > 0){
               $distance_amount = (ceil($expect / $config['exceed_base_distance_number']) * $config['exceed_base_distance']);
           }
            $expectW = $totalWeight - $config['base_distribution_weight'];
            if($expectW <= 0){
                $expectW = 0;
            }
            $weight_amount = 0;
            if($config['base_distribution_weight'] > 0 && $totalWeight > $config['base_distribution_weight']){
                $weight_amount += (ceil($expectW / $config['exceed_base_weight_number']) * $config['exceed_base_weight']);
            }
    	    $tData[$vv['id']] = array(
    				'merchant_id'=>(string)$vv['id'],
    				'shipping_fee'=>sprintf('%.2f',$this->mDln->getIncome($vv['distance']/1000,ceil($totalWeight))),
                    'base_amount'=>sprintf('%.2f',$config['base_distribution_fee']),//基础邮费
                    'base_weight'=>sprintf('%.2f',$config['base_distribution_weight']),//基础重量
                    'distance'=>sprintf('%.2f',$vv['distance']),//距离
                    'weight'=>sprintf('%.2f',$totalWeight),//总重量
    	            'distance_amount'=> sprintf('%.2f',$distance_amount),//超出距离/费用
    	            'weight_amount'=> sprintf('%.2f',$weight_amount),//超出重量/费用
                    'exceed_distance'=>sprintf('%.2f',$expect * 1000),//超出距离
                    'exceed_weight'=>sprintf('%.2f',$expectW),//超出重量
                    'is_free_shipping'=>1,
    		);
    	}
    	
    	return $tData;
    }
    
}